//
//  LoginNewViewController.m
//  JiaoWuGuanLi
//
//  Created by Zinzie on 14-2-17.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//

#import "LoginNewViewController.h"
#import "UIView+XHCustomHUD.h"
#import "TFHpple.h"

@interface LoginNewViewController ()
@property (strong, nonatomic) AFHTTPRequestOperationManager *AFHROM;
@property (weak,nonatomic) NSString *viewState;

@end

@implementation LoginNewViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated{
    
	// 显示验证码

}
-(void)viewDidAppear:(BOOL)animated{
    
    self.checked = NO;
	// Do any additional setup after loading the view.
    //这编辑self.yanZhengImage
    [self.zhangHao becomeFirstResponder];
    AFNetworkReachabilityManager *man=[AFNetworkReachabilityManager sharedManager];
    if (man.reachable) {
        NSLog(@"网络是否能连接");
    }else{
        NSLog(@"无网络连接");
    }
    NSMutableURLRequest *UrlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://172.21.96.64/CheckCode.aspx"]];
    if(self.AFHROM.cookieDictionary) {
        [UrlRequest setHTTPShouldHandleCookies:NO];
        [UrlRequest setAllHTTPHeaderFields: self.AFHROM.cookieDictionary];
    }
    [UrlRequest setTimeoutInterval:1];
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:UrlRequest];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode==200) {
            NSLog(@"Response: %@", responseObject);
            self.yanZhengImage.image = responseObject;
        }else
            NSLog(@"加载验证码失败");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);
    }];
    [requestOperation start];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)nextPressed {

    [self.Mima becomeFirstResponder];
}

- (IBAction)goPressed {
    [self.Mima resignFirstResponder];
    [self.yanZheng becomeFirstResponder];
}
- (IBAction)logIn {
    [self touchOutside];
    if (self.checked == YES) {
        NSString *zhanghao = self.zhangHao.text;
        NSString *mima = self.Mima.text;
        NSLog(@"账号: %@  密码:%@",zhanghao,mima);
        [self loading];

    }
    else{
        [self inputCheck];
    }
    self.checked = NO;
    }

- (IBAction)touchOutside {
    //点击其他地方退出键盘
    [self.zhangHao resignFirstResponder];
    [self.Mima resignFirstResponder];
    [self.yanZheng resignFirstResponder];
}

- (IBAction)didFinish {
    [self.yanZheng resignFirstResponder];
    [self logIn];
}

-(void)loading{
    [self.view showHUDWithText:@"登录中" hudType:kXHHUDLoading animationType:kXHHUDFade delay:0];
    self.AFHROM.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.AFHROM.requestSerializer = [AFHTTPRequestSerializer serializer];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    
    self.AFHROM.requestSerializer.stringEncoding = enc;
    NSDictionary *parameters = @{@"__VIEWSTATE":@"dDwtMTg3MTM5OTI5MTs7PkDQD2kYQWAxp4gTWKdd1YunUJ++",@"TextBox1":self.zhangHao.text,@"TextBox2":self.Mima.text,@"TextBox3":self.yanZheng.text,@"RadioButtonList1":@"学生",@"Button1":@""};
    
    [self.AFHROM POST:@"http://172.21.96.64/default2.aspx" parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"biaodantijiaochenggong:%ld，%@",(long)operation.response.statusCode,operation.responseString);//提交表单
                            NSString *utf8HtmlStr = [operation.responseString stringByReplacingOccurrencesOfString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" withString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"];
              NSData *htmlDataUTF8 = [utf8HtmlStr dataUsingEncoding:NSUTF8StringEncoding];
              TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:htmlDataUTF8];
              NSArray *elements  = [xpathParser searchWithXPathQuery:@"//input[@name='__VIEWSTATE']"];
              
              // Access the first cell
              TFHppleElement *element = [elements objectAtIndex:0.2];
              
              // Get the text within the cell tag
              NSString *content = [element text];
              NSString *ta=[element tagName];
              self.viewState=[element objectForKey:@"value"];
              NSLog(@"学号姓名为%@%@",content,ta);
              //Get all the cells of the 2nd row of the 3rd table
              NSURL *denglu=[NSURL URLWithString:@"http://172.21.96.64/default2.aspx"];
              if ([operation.response.URL isEqual:denglu]) {
                  [self miMaCuoWu];
              }else{
                  [self chengGong];
              }
              
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"Error: %@", @"???");
          }];
    

    
}
- (IBAction)chengGong {
    [self.view dismissHUD:self.view.hudView delay:0];
    [self performSelector:@selector(chengGongStep2) withObject:self afterDelay:0.15];
}

-(void)chengGongStep2{
    [self.view showHUDWithText:@"登录成功" hudType:kXHHUDSuccess animationType:kXHHUDFade delay:0.7];
//    [self performSelector:@selector(tuiChuJieMian) withObject:Nil afterDelay:0.7];
    
}
-(void)tuiChuJieMian{
    [self.navigationController popViewControllerAnimated:YES];

}

- (IBAction)miMaCuoWu {
    [self.view dismissHUD:self.view.hudView delay:0];
    [self performSelector:@selector(miMaCuoWuStep2) withObject:self afterDelay:0.2];
    [self huanYanzheng];
    
}

-(void)miMaCuoWuStep2{
    [self.view showHUDWithText:@"学号或密码错误" hudType:kXHHUDError animationType:kXHHUDFade delay:1];
    
}

-(void)inputCheck{
    if ([self.zhangHao.text isEqualToString:@""]) {
        [self.zhangHao becomeFirstResponder];
    }
        else if ([self.Mima.text isEqualToString:@""]){
        [self.Mima becomeFirstResponder];
            }
            else if ([self.yanZheng.text isEqualToString:@""]){
                [self.yanZheng becomeFirstResponder];
                }
            else {
                self.checked = YES;
                [self logIn];
            }
}


- (IBAction)huanYanzheng {
    NSLog(@"验证码改变");
    AFNetworkReachabilityManager *man=[AFNetworkReachabilityManager sharedManager];
    if (man.reachable) {
        NSLog(@"网络是否能连接");
    }else{
        NSLog(@"无网络连接");
    }
    NSMutableURLRequest *UrlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://172.21.96.64/CheckCode.aspx"]];
    if(self.AFHROM.cookieDictionary) {
        [UrlRequest setHTTPShouldHandleCookies:NO];
        [UrlRequest setAllHTTPHeaderFields: self.AFHROM.cookieDictionary];
    }
    [UrlRequest setTimeoutInterval:1];
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:UrlRequest];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode==200) {
            NSLog(@"Response: %@", responseObject);
            self.yanZhengImage.image = responseObject;
        }else
            NSLog(@"加载验证码失败");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);
    }];
    [requestOperation start];
	// 显示验证码

}
-(AFHTTPRequestOperationManager*)AFHROM{
    if (!_AFHROM) {
        
        _AFHROM=[AFHTTPRequestOperationManager manager];
        return _AFHROM;
    }
    return _AFHROM;
}

@end
